<?php
/**
 * SocialEngine
 *
 * @category   Application_Extensions
 * @package    Page
 * @copyright  Copyright Hire-Experts LLC
 * @license    http://www.hire-experts.com
 * @version    $Id: PageController.php 2010-08-31 16:05 idris $
 * @author     Idris
 */

/**
 * @category   Application_Extensions
 * @package    Page
 * @copyright  Copyright Hire-Experts LLC
 * @license    http://www.hire-experts.com
 */

class Page_PageController extends Core_Controller_Action_Standard {
	public function init() {
		$page_id = $this->_getParam ( 'page_id' );
		$this->view->page = $page = Engine_Api::_ ()->getItem ( 'page', $page_id );
		
		if ($page == null) {
			$this->_redirectCustom ( array ('route' => 'page_browse' ) );
			return;
		}
		
		if (! $this->_helper->requireUser ()->isValid () || ! $page->isTeamMember ()) {
			$this->_redirectCustom ( array ('route' => 'page_browse' ) );
			return;
		}
	}
	
	public function deleteAction() {
		$page_id = $this->_getParam ( 'page_id' );
		$page = $this->view->page;
		
		$this->view->form = $form = new Page_Form_Delete ();
		
		$form->setAction ( $this->view->url ( array ('action' => 'delete', 'page_id' => $page_id ), 'page_team' ) );
		$description = sprintf ( Zend_Registry::get ( 'Zend_Translate' )->_ ( 'PAGE_DELETE_DESC' ), $this->view->htmlLink ( $page->getHref (), $page->getTitle () ) );
		
		$form->setDescription ( $description );
		
		if (! $this->getRequest ()->isPost ()) {
			return;
		}
		
		$db = Engine_Api::_ ()->getDbtable ( 'pages', 'page' )->getAdapter ();
		$db->beginTransaction ();
		
		try {
			$page->delete ();
			$db->commit ();
		} catch ( Exception $e ) {
			$db->rollBack ();
			throw $e;
		}
		
		$this->_redirectCustom ( array ('route' => 'page_manage' ) );
	}
	
	public function deletePhotoAction() {
		$page_id = $this->_getParam ( 'page_id' );
		$page = $this->view->page;
		
		$page->removePhotos ();
		$page->photo_id = 0;
		$page->save ();
		
		$this->_redirectCustom ( array ('route' => 'page_team', 'action' => 'edit', 'page_id' => $page_id ) );
	}
	
	public function editAction() {
		$table = Engine_Api::_ ()->getDbtable ( 'themes', 'core' );
		$activeTheme = $this->view->activeTheme = $table->fetchRow ( $table->select ()->where ( 'active = ?', 1 ) );
		
		$page_id = $this->_getParam ( 'page_id' );
		$page = $this->view->page;
		
		$aliasedFields = $page->fields ()->getFieldsObjectsByAlias ();
		$this->view->topLevelId = $topLevelId = 0;
		$this->view->topLevelValue = $topLevelValue = null;
		
		if (isset ( $aliasedFields ['profile_type'] )) {
			$aliasedFieldValue = $aliasedFields ['profile_type']->getValue ( $page );
			$topLevelId = $aliasedFields ['profile_type']->field_id;
			$topLevelValue = (is_object ( $aliasedFieldValue ) ? $aliasedFieldValue->value : null);
			if (! $topLevelId || ! $topLevelValue) {
				$topLevelId = null;
				$topLevelValue = null;
			}
			$this->view->topLevelId = $topLevelId;
			$this->view->topLevelValue = $topLevelValue;
		}
		
		$this->view->privacyForm = $privacyForm = new Page_Form_Privacy ();
		$this->view->fieldForm = $fieldForm = new Page_Form_Edit ( array ('item' => $page, 'topLevelId' => $topLevelId, 'topLevelValue' => $topLevelValue ) );
		$this->view->photoForm = $photoForm = new Page_Form_Photo ();
		$this->view->admins = $page->getAdmins ();
		
		$privacyForm->setAction ( $this->view->url ( array ('action' => 'edit', 'page_id' => $page_id ), 'page_team' ) );
		$fieldForm->setAction ( $this->view->url ( array ('action' => 'edit', 'page_id' => $page_id ), 'page_team' ) );
		$photoForm->setAction ( $this->view->url ( array ('action' => 'edit', 'page_id' => $page_id ), 'page_team' ) );
		
		$auth = Engine_Api::_ ()->authorization ()->context;
		
		$roles = array ('team', 'likes', 'registered', 'everyone' );
		foreach ( $roles as $roleString ) {
			$role = $roleString;
			
			if ($role === 'team') {
				$role = $page->getTeamList ();
			} elseif ($role === 'likes') {
				$role = $page->getLikesList ();
			}
			
			if (1 === $auth->isAllowed ( $page, $role, 'view' ) && ! empty ( $privacyForm->auth_view )) {
				$privacyForm->auth_view->setValue ( $roleString );
			}
		}
		
		$roles = array ('team', 'likes', 'registered' );
		foreach ( $roles as $roleString ) {
			$role = $roleString;
			
			if ($role === 'team') {
				$role = $page->getTeamList ();
			} elseif ($role === 'likes') {
				$role = $page->getLikesList ();
			}
			
			if (1 === $auth->isAllowed ( $page, $role, 'comment' ) && ! empty ( $privacyForm->auth_comment )) {
				$privacyForm->auth_comment->setValue ( $roleString );
			}
		}
		
		$roles = array ('team', 'likes', 'registered' );
		foreach ( $roles as $roleString ) {
			$role = $roleString;
			
			if ($role === 'team') {
				$role = $page->getTeamList ();
			} elseif ($role === 'likes') {
				$role = $page->getLikesList ();
			}
			
			if (1 === $auth->isAllowed ( $page, $role, 'posting' ) && ! empty ( $privacyForm->auth_posting )) {
				$privacyForm->auth_posting->setValue ( $roleString );
			}
		}
		
		$privacyForm->search->setValue ( $page->search );
		
		if ($this->getRequest ()->isPost ()) {
			try {
				$db = Engine_Api::_ ()->getDbTable ( 'pages', 'page' )->getAdapter ();
				$this->view->edit = $edit = $this->_getParam ( 'edit' );
				
				switch ($edit) {
					case 'info' :
						if ($fieldForm->isValid ( $this->getRequest ()->getPost () )) {
							$fieldForm->saveValues ();
							if ($fieldForm->getSubForm ( 'extra' )->isValid ( $this->_getParam ( 'extra' ) )) {
								$values = $this->_getParam ( 'extra' );
								$address = array ($values ['country'], $values ['city'], $values ['street'] );
								
								if ($address [0] == '' && $address [1] == '' && $address [2] == '') {
									$page->deleteMarker ();
								} elseif ($page->isAddressChanged ( $address )) {
									$page->addMarkerByAddress ( $address );
								}
								
								$raw_tags = preg_split ( '/[,]+/', $values ['tags'] );
								$tags = array ();
								foreach ( $raw_tags as $tag ) {
									$tag = trim ( strip_tags ( $tag ) );
									if ($tag == "") {
										continue;
									}
									$tags [] = $tag;
								}
								$page->tags ()->addTagMaps ( Engine_Api::_ ()->user ()->getViewer (), $tags );
								
								//								$values['description'] = utf8_encode($values['description']);
								//                $values['title'] = utf8_encode($values['title']);
								

								$page->setFromArray ( $values );
								$page->displayname = $page->title;
								$page->keywords = $values ['tags'];
							}
							
							$fieldForm->setAttrib ( 'class', 'page_edit_form' );
							$fieldForm->addNotice ( Zend_Registry::get ( 'Zend_Translate' )->_ ( 'Chagnes were successfully saved.' ) );
						}
						break;
					case 'photo' :
						if ($photoForm->isValid ( $this->getRequest ()->getPost () )) {
							if ($photoForm->photo->getValue () !== null) {
								$page->setPhoto ( $photoForm->photo );
							}
							$photoForm->setAttrib ( 'class', 'form-wrapper page_edit_form' );
							$photoForm->addNotice ( Zend_Registry::get ( 'Zend_Translate' )->_ ( 'Image was successfully proccessed.' ) );
						}
						break;
					case 'privacy' :
						if ($privacyForm->isValid ( $this->getRequest ()->getPost () )) {
							$values = $privacyForm->getValues ();
							$page->setPrivacy ( $values );
							$page->search = $values ['search'];
							
							$privacyForm->setAttrib ( 'class', 'page_edit_form' );
							$privacyForm->addNotice ( Zend_Registry::get ( 'Zend_Translate' )->_ ( 'Settings were successfully saved.' ) );
						}
						break;
					default :
						throw new Exception ( Zend_Registry::get ( 'Zend_Translate' )->_ ( 'Do not specified editting type.' ) );
						break;
				}
				
				$page->modified_date = date ( 'Y-m-d H:i:s' );
				$page->save ();
				$db->commit ();
			} catch ( Exception $e ) {
				$db->rollBack ();
				throw $e;
			}
		}
		
		$tags = $page->tags ()->getTagMaps ();
		$tagString = '';
		foreach ( $tags as $tagmap ) {
			if ($tagString !== '')
				$tagString .= ', ';
			$tagString .= $tagmap->getTag ()->getTitle ();
		}
		
		$fieldForm->getSubForm ( 'extra' )->tags->setValue ( $tagString );
		$fieldForm->getSubForm ( 'extra' )->populate ( $page->toArray () );
		//		
		//		$fieldForm->getSubForm('extra')->description->setValue($page->getDescription());
		//		$fieldForm->getSubForm('extra')->title->setValue($page->getTitle());
		

		$photoForm->populate ( $page->toArray () );
	}
	
	public function postNoteAction() {
		$page_id = $this->_getParam ( 'page' );
		$note = $this->_getParam ( 'note' );
		$page = $this->view->page;
		
		$page->note = trim ( strip_tags ( $note ) );
		$page->save ();
		$this->view->note = nl2br ( $page->note );
		$this->view->result = 1;
		$this->view->message = "Ok!";
	}

}